package dev.pda.display.presentation.page.widgets

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import java.util.*

class UrlView : LinearLayout {

    private var webView: WebView? = null

    companion object {
        private const val HTTP = "http"
        private const val HTTPS = "https://"
    }

    constructor(context: Context?) : super(context) {
        init(null)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs)
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun init(attrs: AttributeSet?) {
        webView = WebView(context)
        webView?.webViewClient = HtmlWebViewClient()
        webView?.settings?.javaScriptEnabled = true
        webView?.settings?.useWideViewPort = true
        webView?.settings?.loadWithOverviewMode = true
        webView?.clearCache(true)
        this.addView(webView)
    }

    fun loadUrl(url: String) {
        webView?.loadUrl(if (url.toLowerCase(Locale.ROOT).startsWith(HTTP)) url else HTTPS + url)
    }

    private class HtmlWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView,
            url: String
        ): Boolean {
            return false
        }
    }
}